package flex.cc.order.manage.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import flex.cc.PublicUtil;
import flex.cc.base.dto.LoginAuthDto;
import flex.cc.common.vo.DelayedConfig;
import flex.cc.core.utils.RequestUtil;
import flex.cc.order.manage.dao.OrderMainDao;
import flex.cc.order.manage.dto.order.OrderImgEntity;
import flex.cc.order.manage.dto.order.OrderMainEntity;
import flex.cc.order.manage.dto.order.OrderTrackEntity;
import flex.cc.order.manage.dto.vo.OrderMainVo;
import flex.cc.order.manage.service.OrderImgService;
import flex.cc.order.manage.service.OrderMainService;
import flex.cc.order.manage.service.OrderTrackService;
import flex.cc.system.dao.DictCodeDao;
import flex.cc.system.entity.DictCodeEntity;
import flex.cc.uac.entity.UacUserAreaEntity;
import flex.cc.uac.service.UacUserAreaService;
import flex.cc.util.DateUtil;

import java.util.*;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * @author wkangle
 * @className OrderCustomerServiceImpl
 * @description 服务单主表service实现类
 * @time 2021-09-06 15:53:10
 */
@Service("orderMainService")
@Transactional(rollbackFor = Exception.class)
public class OrderMainServiceImpl extends ServiceImpl<OrderMainDao, OrderMainEntity> implements OrderMainService {

	@Resource
    private OrderMainDao orderMainDao;
	@Autowired
	private DictCodeDao dictCodeDao;
	@Autowired
	private OrderTrackService orderTrackService;
	@Autowired
	private OrderImgService orderImgService;
	@Resource
	private UacUserAreaService uacUserAreaService;

	/**
	 * @description 添加一条记录
	 * @param orderMainEntity
	 * @return
	 * @author wkangle
	 * @time 2021/09/08 0008 8:58
	 * @exception/throws
	*/
	public int insert(OrderMainEntity orderMainEntity){
		return orderMainDao.insert(orderMainEntity);
	}

    /**
	 *
	 * @author WANGCONG
	 * 2021年9月7日下午3:20:34
	 * @desc 服务单催单次数记录+1
	 */
	@Override
	public Integer addUrgeCount(String orderNo, Date urgeTime, Date updateTime, String updater) {
		return orderMainDao.addUrgeCount(orderNo, urgeTime, updateTime, updater);
	}

	/**
	 *
	 * @author WANGCONG
	 * 2021年9月7日下午8:41:02
	 * @desc 服务单分页查询
	 */
	@Override
	public IPage<OrderMainVo> queryOrderListWithPage(OrderMainVo orderMain, LoginAuthDto loginAuthDto) {
		Page<OrderMainVo> page = new Page<>(orderMain.getPageNum(),orderMain.getPageSize());
		Long userId = loginAuthDto.getUserId();
		UacUserAreaEntity userArea = uacUserAreaService.queryUserAreaByUserId(userId);
		if (PublicUtil.isNotEmpty(userArea)) {
			if ("01".equals(userArea.getType())) {
				// 用户类型：公司内勤
				String[] cities = null;
				String[] areas = null;
				String[] provinceArr = orderMain.getProvinceArr();
				String[] cityArr = orderMain.getCityArr();
				String[] areaArr = orderMain.getAreaArr();
				String provinceName = userArea.getProvinceName();
				if (!StringUtils.isEmpty(provinceName)) {
					String[] provinces = provinceName.split(",");
					String cityName = userArea.getCityName();
					if (!StringUtils.isEmpty(cityName)) {
						cities = cityName.split(",");
					}
					String areaName = userArea.getAreaName();
					if (!StringUtils.isEmpty(areaName)) {
						areas = areaName.split(",");
					}
					if (!StringUtils.isEmpty(provinceArr) && provinceArr.length > 0) {
						Set<String> sameProvinces = getSameElement(provinceArr, provinces);
						if (sameProvinces.size() > 0) {
							// 用户类型公司内勤且查询机构省级【重复】--重复（省）
							orderMain.setProvinceArr((String[]) sameProvinces.toArray());
							if (!StringUtils.isEmpty(cities)) {
								if (!StringUtils.isEmpty(cityArr) && cityArr.length > 0) {
									Set<String> sameCities = getSameElement(cityArr, cities);
									if (sameCities.size() > 0) {
										// 用户类型公司内勤且查询机构市级【重复】--重复（市）
										orderMain.setCityArr((String[]) sameCities.toArray());
										if (!StringUtils.isEmpty(areas)) {
											if (!StringUtils.isEmpty(areaArr) && areaArr.length > 0) {
												Set<String> sameAreas = getSameElement(areaArr, areas);
												if (sameAreas.size() > 0) {
													// 用户类型公司内勤且查询机构区级【重复】--重复（区）
													orderMain.setAreaArr((String[]) sameAreas.toArray());
												}else {
													// 用户类型公司内勤且查询机构区级【没有重复】——用户权限（区）
													orderMain.setAreaArr(areas);
												}
											}else {
												// 用户类型公司内勤且查询机构区级【没有值】——用户权限（区）
												orderMain.setAreaArr(areas);
											}
										}
									}else {
										// 用户类型公司内勤且查询机构市级【没有重复】——用户权限（市、区）
										orderMain.setCityArr(cities);
										orderMain.setAreaArr(areas);
									}
								}else {
									// 用户类型公司内勤且查询机构市级【没有值】——用户权限（市、区）
									orderMain.setCityArr(cities);
									orderMain.setAreaArr(areas);
								}
							}
						}else {
							// 用户类型公司内勤且查询机构省级【没有重复】——用户权限（省、市、区）
							orderMain.setProvinceArr(provinces);
							orderMain.setCityArr(cities);
							orderMain.setAreaArr(areas);
						}
					}else {
						// 用户类型公司内勤且查询机构省级【没有值】——用户权限（省、市、区）
						orderMain.setProvinceArr(provinces);
						orderMain.setCityArr(cities);
						orderMain.setAreaArr(areas);
					}
				}
			}else if ("02".equals(userArea.getType())) {
				// 用户类型：渠道商
				String channelCode = userArea.getChannelCode();
				if (!StringUtils.isEmpty(channelCode)) {
					String[] channelArr = channelCode.split(",");
					orderMain.setChannelArr(channelArr);
				}
			}else if ("03".equals(userArea.getType())) {
				// 用户类型：服务商
				String serviceCode = userArea.getServiceCode();
				if (!StringUtils.isEmpty(serviceCode)) {
					String[] serviceArr = serviceCode.split(",");
					orderMain.setServiceArr(serviceArr);
				}
			}
		}
    	IPage<OrderMainVo> pageData=orderMainDao.queryOrderListWithPage(page, orderMain);
    	return pageData;
	}

	/**
	 *
	 * @param arr1
	 * @param arr2
	 * @return
	 */
	private Set<String> getSameElement(String[] arr1, String[] arr2){
		Set<String> same = new HashSet<>();  //用来存放两个数组中相同的元素
		Set<String> temp = new HashSet<>();  //用来存放数组a中的元素
		for (int i = 0; i < arr1.length; i++) {
			temp.add(arr1[i]);   //把数组a中的元素放到Set中，可以去除重复的元素
		}
		for (int j = 0; j < arr2.length; j++) {
			//把数组b中的元素添加到temp中
			//如果temp中已存在相同的元素，则temp.add（b[j]）返回false
			if(!temp.add(arr2[j]))
				same.add(arr2[j]);
		}
		return same;
	}

	/**
	 *
	 * @author WANGCONG
	 * 2021年9月8日下午1:17:14
	 * @desc 服务单部分导出
	 */
	@Override
	public IPage<OrderMainVo> queryOrderListWithDataIds(OrderMainVo vo) {
		Page<OrderMainVo> page = new Page<>(vo.getPageNum(),vo.getPageSize());
		return orderMainDao.queryOrderListWithDataIds(page, vo);
	}


	/**
	 *
	 * @author WANGCONG
	 * 2021年9月8日下午6:13:32
	 * @desc 服务单全部导出
	 */
	@Override
	public IPage<OrderMainVo> exportOrder(OrderMainVo orderMain) {
		Page<OrderMainVo> page = new Page<>(orderMain.getPageNum(),orderMain.getPageSize());
		return orderMainDao.exportOrder(page, orderMain);
	}

	/**
	 *
	 * @author WANGCONG
	 * 2021年9月8日下午7:25:22
	 * @desc 根据dataId集合查询催单信息
	 */
	@Override
	public List<OrderMainVo> queryMainByDataIds(OrderMainVo orderMain) {
		return orderMainDao.queryMainByDataIds(orderMain);
	}

	/**
	 * @description 根据查询条件查询服务单主表信息
	 * @param params 查询条件
	 * @return
	 * @author wkangle
	 * @time 2021/09/08 0008 9:12
	 * @exception/throws
	 */
	@Override
	public OrderMainEntity	getOneByParams(Map<String, Object> params){
		return orderMainDao.getOneByParams(params);
	}


	/**
	 * @param dataId 服务单id
	 * @param status 状态
	 * @return
	 * @description 修改服务单状态
	 * @author wkangle
	 * @time 2021/09/08 0008 17:31
	 * @exception/throws
	 */
	@Override
	public int updateStatus(String dataId, String status, Date updateTime, String updater) {
		return orderMainDao.updateStatus(dataId, status, updateTime, updater);
	}

	/**
	 * @description 更新
	 * @param orderMainEntity
	 * @return
	 * @author wkangle
	 * @time 2021/09/09 0009 13:34
	 * @exception/throws
	 */
	@Override
	public int update(OrderMainEntity orderMainEntity){
		orderMainEntity.setUpdater(RequestUtil.getLoginUser().getUserCode());
		orderMainEntity.setUpdateTime(new Date());
		return orderMainDao.update(orderMainEntity);
	}

	/**
	 *
	 * @author WANGCONG
	 * 2021年9月10日下午6:01:38
	 * @desc 根据dataId更新延时标识
	 */
	@Override
	public int updateDelayedFlag(String dataId) {
		return orderMainDao.updateDelayedFlag(dataId);
	}

	/**
	 *
	 * @author WANGCONG
	 * 2021年9月28日上午8:51:24
	 * @desc 去除延时标识
	 */
	@Override
	public int delDelayedFlag(String dataId) {
		return orderMainDao.delDelayedFlag(dataId);
	}

	/**
	 *
	 * @author WANGCONG
	 * 2021年9月28日上午10:22:36
	 * @desc 批量更新延时单标识
	 */
	@Override
	public int batchUpdateDalay(OrderMainVo orderMainVo) {
		int result = 0;
		Date currentTime = new Date();
		Page<OrderMainVo> page = new Page<>(orderMainVo.getPageNum(),orderMainVo.getPageSize());
		IPage<OrderMainVo> pageData = orderMainDao.queryDalayList(page, orderMainVo);
		List<OrderMainVo> dalayList = pageData.getRecords();
		List<String> dataIdList = new ArrayList<String>();
		for(int i=0; i<dalayList.size(); i++){
			OrderMainVo vo = dalayList.get(i);
			String status = vo.getStatus();
			Date synTime = vo.getSynTime();
			if("02".equals(status)){ //已受理,判断已受理--到当前时间，处理时长超过5分钟，更新延时标识
				int differ = DateUtil.getIntervalFen(synTime, currentTime);
				if (differ >= DelayedConfig.ONE){
					dataIdList.add(vo.getDataId());
				}
			}else{ //已接单,判断已接单--到当前时间，处理时长超过55分钟，更新延时标识
				int differ = DateUtil.getIntervalFen(synTime, currentTime);
				if (differ >= DelayedConfig.TWO){
					dataIdList.add(vo.getDataId());
				}
			}
		}
		if(dataIdList.size() > 0){
			result = orderMainDao.batchUpdateDalay(dataIdList);
		}
		return result;
	}
	/**
     * 投诉模糊查询服务单号
     * */
	@Override
	public List<Map<String,String>> querySearchAsync(OrderMainVo vo) {
		List<Map<String,String>> querySearchAsync = orderMainDao.querySearchAsync(vo);
		return querySearchAsync;
	}

	@Override
	public OrderMainVo queryOrderByNo(OrderMainVo vo) {
		return orderMainDao.queryOrderByNo(vo);
	}

	/**
	 *
	 * @author WANGCONG
	 * 2021年10月20日下午2:04:06
	 * @desc 根据dataId集合查询服务单的服务类型、省市区
	 */
	@Override
	public List<OrderMainVo> matchRule(OrderMainVo orderMain) {
		return orderMainDao.matchRule(orderMain);
	}

	@Override
	public IPage<OrderMainVo> queryOrderListInfoPage(OrderMainVo  orderMainVo) {
		Page<OrderMainVo> page = new Page<>(orderMainVo.getPageNum(),orderMainVo.getPageSize());
    	IPage<OrderMainVo> pageData=orderMainDao.queryOrderListInfoPage(page, orderMainVo);
    	List<OrderMainVo> list= pageData.getRecords();
    	Map<String,String> map1=new HashMap<String,String>();
    	DictCodeEntity code=new DictCodeEntity();
		code.setTypeCode("serviceItem");
		List<DictCodeEntity> dictList = dictCodeDao.getdictCodeList(code);
		if(dictList!=null&&dictList.size()>0) {
			for (DictCodeEntity d : dictList) {
				map1.put(d.getCode(),d.getValue());
			}
		}
		for(OrderMainVo order:list) {
			if(!PublicUtil.isEmpty(order.getServiceItem()) ) {
				String[] serviceItem=order.getServiceItem().split(",");
				String cbkind="";
				for(int i = 0; i < serviceItem.length; i++) {
   	    			if(i == serviceItem.length-1){
   	    				cbkind += map1.get(serviceItem[i]) ;
   	  			    }else{
   	  			    	cbkind += map1.get(serviceItem[i]) + "," ;
   	  			    }
   	    		 }
				order.setServiceItem(cbkind);
			}
		}
    	return pageData;
	}

	@Override
	public OrderMainVo getRescueDetails(String orderNo) {
		OrderMainVo vo=orderMainDao.getRescueDetailsList(orderNo);
		DictCodeEntity code=new DictCodeEntity();
		code.setTypeCode("serviceItem");
		List<DictCodeEntity> dictList = dictCodeDao.getdictCodeList(code);
		Map<String,String> map1=new HashMap<String,String>();
		if(dictList!=null&&dictList.size()>0) {
			for (DictCodeEntity d : dictList) {
				map1.put(d.getCode(),d.getValue());
			}
		}
		if(!PublicUtil.isEmpty(vo)) {
			if(!PublicUtil.isEmpty(vo.getServiceItem())) {
				vo.setServiceItem(map1.get(vo.getServiceItem()));
			}
			List<OrderTrackEntity> task=orderTrackService.selectOrderTrackList(orderNo);
			if(!PublicUtil.isEmpty(task)) {
				vo.setListOrderTrack(task);
			}
			List<OrderImgEntity> img=orderImgService.queryImgByOrderNo(orderNo);
			if(!PublicUtil.isEmpty(img)) {
				vo.setListOrderImg(img);
			}
		}
		return vo;
	}

	@Override
	public String checkFwOrderStatus(OrderMainVo vo) {
		String flag = "0";
		List<OrderMainEntity> list = orderMainDao.checkFwOrderStatus(vo);
		if(PublicUtil.isNotEmpty(list)) {
			flag = "1";
		}
		return flag;
	}

	@Override
	public void updateEvaluateByNo(OrderMainVo vo) {
		orderMainDao.updateEvaluateByNo(vo);
	}

	@Override
	public Integer addOaUrgeCount(String orderNo, Date oaurgeTime, Date updateTime, String updater) {

		return orderMainDao.addOaUrgeCount(orderNo, oaurgeTime, updateTime, updater);
	}

	/**
	 *
	 * @author WANGCONG
	 * 2022年1月6日下午3:01:15
	 * @desc 更新取消渠道来源字段信息
	 */
	@Override
	public int updateCancelChannel(String dataId, Date date, String cancelChannel) {
		return orderMainDao.updateCancelChannel(dataId, date, cancelChannel);
	}

	/**
	 *
	 * @author WANGCONG
	 * 2022年3月3日下午13:48:58
	 * @desc 根据来源单号查询实体信息
	 */
	@Override
	public OrderMainEntity queryByOwnerOrderNo(String ownerOrderNo) {
		return orderMainDao.queryByOwnerOrderNo(ownerOrderNo);
	}

}
